package pers.cj.pdos.listener;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import pers.cj.pdos.utils.FileProperUtil;
import pers.cj.pdos.utils.Logger;

import java.io.*;

public class StartListener implements ApplicationListener {
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        try {
            checkDir();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void checkDir() throws IOException {
        Logger.getLogger(getClass()).info("开始检查");
        for (String key : FileProperUtil.getInstance().propertyNames()) {
            String dir = FileProperUtil.getInstance().getVal(key);
            File file = new File(dir);
            if (!file.exists()) {
                Logger.getLogger(getClass()).info(key + "对应的目录【"+dir+"】不存在,需要创建");
                file.mkdirs();
            }
        }

        //默认logo处理
        String defaultLogo = FileProperUtil.getInstance().getVal("image.company")+ "defaultLogo.png";
        File file = new File(defaultLogo);
        if (!file.exists()) {
            Logger.getLogger(getClass()).info( "defaultLogo不存在，需要创建");
            InputStream inputStream = getClass().getResourceAsStream("/template/defaultLogo.png");
            OutputStream out=new FileOutputStream(defaultLogo);

            byte[] buff=new byte[1024];
            int b;
            while ((b=inputStream.read(buff))!=-1) {
                out.write(buff,0,b);
            }
            inputStream.close();
            out.close();
            Logger.getLogger(getClass()).info("defaultLogo创建成功");
        } else {
            Logger.getLogger(getClass()).info( "defaultLogo已存在");
        }
    }
}
